/**
 * <p>Title: ServiceZMCMF0.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午04:51:46  张小飞  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMReceiveGoods;
import com.baosight.sczx.zm.cm.domain.ZMCMReceiveGoodsInfo;
import com.baosight.sczx.zm.cm.domain.ZMCMStockPlanDetail;

/**
 * <p>Title: ServiceZMCMF0.java</p>
 * <p>Description: 到货登记管理-到货记录</p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-5 下午04:51:46  张小飞  Create
 *</pre>
 */
public class ServiceZMCMF0 extends ServiceEPBase {

	/**
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMF0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:36:49 张小飞
	 * </p>
	 *
	*/
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		EiInfo outInfo = this.query(inInfo);
		outInfo.addBlock(generateIsAndNot());
		return outInfo;
	}
	
	/**
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMF0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:36:49 张小飞
	 * </p>
	 *
	*/
	@Override
	public EiInfo query(EiInfo inInfo) {
		StaticTools.setQueryParameters(inInfo, "fdStatus", "正常", true);
		EiInfo outInfo = super.query(inInfo, "ZMCMReceiveGoods.query", new ZMCMReceiveGoods());
		return outInfo;
	}
	
	/**
	 * <p>Function: insert</p>
	 * <p>Description: 新增</p>
	 * <p>return value: ServiceZMCMF0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:36:49 张小飞
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public EiInfo insert(EiInfo inInfo) {
		
		//插入到货登记表一条记录
		String rgKey = TablePk.getInstance().getNextValue("T_CM_RECEIVEGOODS");
		inInfo.getBlock("result").setCell(0, "fdKeyId", rgKey);
		inInfo.getBlock("result").setCell(0, "fdYear", StaticTools.getYear());
		inInfo.getBlock("result").setCell(0, "fdMonth", Integer.parseInt(StaticTools.getMonth()));
		inInfo.getBlock("result").setCell(0, "fdStatus", "正常");
		//判断是否来自采购计划
		if(inInfo.getBlocks().containsKey("subBlock"))
		{
			inInfo.getBlock("result").setCell(0, "fdIsfromPlan", "1");
		}
		else
		{
			inInfo.getBlock("result").setCell(0, "fdIsfromPlan", "0");
		}
		EiInfo outInfo = super.insert(inInfo, "ZMCMReceiveGoods.insert");
		
		if(inInfo.getBlocks().containsKey("subBlock"))
		{
			List<String> _list = new ArrayList<String>();
			Map params = new HashMap();
			
			//插入到货明细表记录
			for(int i=0; i < inInfo.getBlock("subBlock").getRowCount(); i++){
				String Sum = inInfo.getBlock("subBlock").getCellStr(i, "fdSum");
				String RecevieSum = inInfo.getBlock("subBlock").getCellStr(i, "fdRecevieSum");
				String ActualNum = inInfo.getBlock("subBlock").getCellStr(i, "fdActualNum");
				String Price = inInfo.getBlock("subBlock").getCellStr(i, "fdPrice");
				double fdSum = (Sum == null)? new Double(0):Double.valueOf(Sum.toString());
				double fdRecevieSum = (RecevieSum == null)? new Double(0):Double.valueOf(RecevieSum.toString());
				double fdActualNum = (ActualNum == null)? new Double(0):Double.valueOf(ActualNum.toString());
				double fdPrice = (Price == null)? new Double(0):Double.valueOf(Price.toString());
				
				if((fdActualNum-(fdSum-fdRecevieSum)) > 0)
				{
					inInfo.setStatus(-1);
					inInfo.setMsg("实收数量不能大于采购数量减已到货数量！");
					return inInfo;
				}
				
				String fdDetailId = inInfo.getBlock("subBlock").getCellStr(i, "fdKeyId");
				inInfo.getBlock("subBlock").setCell(i, "fdKeyId",  TablePk.getInstance().getNextValue("T_CM_RECEIVEGOODSINFO"));
				inInfo.getBlock("subBlock").setCell(i, "fdReceiveId", rgKey);
				inInfo.getBlock("subBlock").setCell(i, "fdDetailId", fdDetailId);
				inInfo.getBlock("subBlock").setCell(i, "fdValidateStatus", "到货");
				inInfo.getBlock("subBlock").setCell(i, "fdReceiveSum", BigDecimal.valueOf(fdActualNum*fdPrice));//此处必须这样赋值，不然会与采购计划表中字段“已到货数量（FD_RECEVIE_SUM）”发生冲突
	
				_list.add(inInfo.getBlock("subBlock").getCellStr(i, "fdMaterialId"));
			}
			
			//判断本次的到货物资中，是否有本年度第一次到货物资
			params.put("fdMaterialIds", _list);
			params.put("fdYear", StaticTools.getYear());
			//List result = dao.query("ZMCMReceiveGoods.validateHasSame", params);
			dao.query("ZMCMReceiveGoods.validateHasSame", params);
//			if(result != null && result.isEmpty()) {
//				outInfo.setMsg("本次的到货物资中含有本年度第一次到货物资，如需调整计划价请进入调价模块！");
//				outInfo.setDetailMsg("本次的到货物资中含有本年度第一次到货物资，如需调整计划价请进入调价模块！");
//			}
			
			super.insert(inInfo, "ZMCMReceiveGoodsInfo.insert", "subBlock");
		}
		
		//更新到货主表单据金额
		Map inMap = new HashMap();
		inMap.put("fdKeyId", rgKey);
		dao.update("ZMCMReceiveGoods.updateSumWithAllDetail", inMap);
		
		//更新采购计划中对应数据信息
		updateStockPlanInfo(rgKey, false);
		
		return outInfo;
	}

	/**
	 * <p>Function: invalid</p>
	 * <p>Description: 作废</p>
	 * <p>return value: ServiceZMCMF0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午03:36:49 张小飞
	 * </p>
	 *
	*/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo invalid(EiInfo inInfo) {
		List<String> _list = new ArrayList<String>();
		Map params = new HashMap();

		for(int i = 0; i < inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++){
			_list.add(inInfo.getBlock("result").getCellStr(i, "fdKeyId"));
		}
		params.put("fdReceiveIds", _list);
		params.put("validate", "yes");
		
		boolean validate = validateTypeManagement(inInfo, params);
		if(validate)
		{
			return inInfo;
		}
		
		validate = canInvalid(inInfo, "ZMCMReceiveGoodsInfo.canInvalid", params);
		if(validate)
		{
			return inInfo;
		}
		else {
			EiInfo _temp = super.update(inInfo, "ZMCMReceiveGoods.invalid");
			
			for(int i=0; i<inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++)
			{
				String fdKeyId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(i, "fdKeyId");
				updateStockPlanInfo(fdKeyId, true);
			}
			
			EiInfo outInfo = this.query(inInfo);
	        outInfo.setMsg(_temp.getMsg());
	        outInfo.setDetailMsg(_temp.getDetailMsg());
	        return outInfo;	
		}

	}
	
	/**
	 * 
	 * <p>Function: updateStockPlanInfo</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午06:55:20 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void updateStockPlanInfo(String fdKeyId, boolean deleteFlag)
	{
		Map inMap = new HashMap();
		inMap.put("fdReceiveId", fdKeyId);
		List<ZMCMReceiveGoodsInfo> _list = dao.query("ZMCMReceiveGoodsInfo.query", inMap);
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMReceiveGoodsInfo info = _list.get(i);
			String fdDetailId = info.getFdDetailId();
			
			if(fdDetailId==null || "no".equals(fdDetailId))
			{
				continue;
			}
			
			Map map = new HashMap();
			map.put("fdKeyId", fdDetailId);
			List<ZMCMStockPlanDetail> detail = dao.query("ZMCMStockPlanDetail.query", map);
			
			String fdStockPlanId = detail.get(0).getFdStockPlanId();
			//double fdSum = detail.get(0).getFdSum();
			double fdRecevieSum = detail.get(0).getFdRecevieSum();
			double fdActualNum = info.getFdActualNum();
			
			//更新采购计划明细信息
			map = new HashMap();
			if(deleteFlag)
			{
				map.put("fdRecevieSum", fdRecevieSum-fdActualNum);
			}
			else
			{
				map.put("fdRecevieSum", fdRecevieSum+fdActualNum);
			}
			
			map.put("fdKeyId", fdDetailId);
			dao.update("ZMCMStockPlanDetail.updateAfterAcceptance", map);
			
			map = new HashMap();
			map.put("fdStockPlanId", fdStockPlanId);
			List<ZMCMStockPlanDetail> detail1 = dao.query("ZMCMStockPlanDetail.query", map);
			
			map = new HashMap();
			map.put("fdPlanStatus", "全部到货");
			for(int j=0; j<detail1.size(); j++)
			{
				double sum = detail1.get(j).getFdSum();
				double recevieSum = detail1.get(j).getFdRecevieSum();
				
				//更新采购计划主表信息
				if(recevieSum != sum)
				{
					map.put("fdPlanStatus", "部分到货");
					break;	
				}
			}
			map.put("fdKeyId", fdStockPlanId);
			dao.update("ZMCMStockPlan.updateAfterAcceptance", map);
		}
	}
	
	/**
	 * 
	 * <p>Function: validateTypeManagement</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午06:55:37 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean validateTypeManagement(EiInfo inInfo, Map idsMap)
	{
		List link = new ArrayList();
		List idList = (List)idsMap.get("fdReceiveIds");
		
		for(int i=0; i<idList.size(); i++)
		{
			String oldKeyId =  (String)idList.get(i);//主键
	        
	    	Map inMap = new HashMap();
			String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
			String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
			if(isUseTypeManagement.equals("1"))
			{
				inMap.put("fdCheckinPeopleId", UserSession.getUserId());
				List _list = dao.query(sqlmap, inMap);
				link = Utils.generateValidateData(_list);
			}
			else
			{
				sqlmap = "ZMCMMaterialType.type";
				List _list = dao.query(sqlmap, inMap);
				for(int k = 0; k<_list.size(); k++)
				{
					Map _map = (Map)_list.get(k);
					link.add(_map.get("fdTypeCode").toString());
				}
			}
	        
			Map<String, String> _map = new HashMap();
			_map.put("fdReceiveId", oldKeyId);
			List<ZMCMReceiveGoodsInfo> list = dao.query("ZMCMReceiveGoodsInfo.query",_map);	
			
			for(int j=0; j<list.size(); j++)
			{
				ZMCMReceiveGoodsInfo detail = list.get(j);
				String materialCode = detail.getFdMaterialCode();
				
				if(materialCode == null || materialCode.equals(""))
				{
					continue;
				}
				
				boolean flag = false;
				for(int k=0; k<link.size(); k++)
				{
					if(materialCode.startsWith(link.get(k).toString()))
					{
						flag = true;
					}
				}
				
				if(!flag)
				{
					inInfo.setStatus(-1);
					inInfo.setMsg("当前登录用户不具有选中到货登记中部分物资的分管权限，不允许作废！");
					return true;
				}
			}
		}
		
		return false;
	}
	
	/**
	 * 
	 * <p>Function: canInvalid</p>
	 * <p>Description: 作废前的校验</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18上午10:47:35 张小飞
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean canInvalid(EiInfo inInfo, String sqlName, Map params) {
		boolean flag = false;
		List<ZMCMReceiveGoodsInfo> result = dao.query(sqlName, params);
		
		if(result != null && result.size() > 0) {
			StringBuffer buffer = new StringBuffer();
			buffer.append("供应商为 ");
			
			for(ZMCMReceiveGoodsInfo info : result){
				buffer.append(info.getFdSupplyName()+" ");
			}
			
			buffer.append("的到货记录中已有办理入库或验收的明细，不允许作废！");
			inInfo.setStatus(-1);
			inInfo.setMsg(buffer.toString());
			flag = true;
		}

		return flag;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private EiBlock generateIsAndNot()
	{
		EiBlock block = new EiBlock("cmes.cm.queryHasImport");
		EiColumn column = new EiColumn("value");
		column.setDescName("值");
		block.getBlockMeta().addMeta(column);
		
		column = new EiColumn("display");
		column.setDescName("名称");
		block.getBlockMeta().addMeta(column);
		
		Map inMap = new HashMap();
		inMap.put("value", "");
		inMap.put("display", "");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "否");
		inMap.put("display", "否");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "是");
		inMap.put("display", "是");
		block.addRow(inMap);
		
		return block;
	}
	
}
